﻿using System;
using System.Windows;
using System.Windows.Interactivity;
using System.Windows.Media;
using Microsoft.Phone.Controls;

namespace FindMyChamp.Helpers
{
    public class OrientationStateBehavior : Behavior<DependencyObject>
    {
        private PhoneApplicationPage _page;

        [System.Windows.Interactivity.CustomPropertyValueEditor(System.Windows.Interactivity.CustomPropertyValueEditor.StateName)]
        public string PortraitState { get; set; }

        [System.Windows.Interactivity.CustomPropertyValueEditor(System.Windows.Interactivity.CustomPropertyValueEditor.StateName)]
        public string LandscapeState { get; set; }

        public OrientationStateBehavior()
        {

        }

        protected override void OnAttached()
        {
            base.OnAttached();

            if (AssociatedObject != null)
            {
                FrameworkElement element = AssociatedObject as FrameworkElement;
                element.Loaded +=new RoutedEventHandler(element_Loaded);
            }
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
        }

        private void element_Loaded(object sender, RoutedEventArgs e)
        {
            var element = sender as FrameworkElement;
            while (element != null)
            {
                if (typeof(PhoneApplicationPage).IsAssignableFrom(element.GetType()))
                {
                    break;
                }
                element = VisualTreeHelper.GetParent(element) as FrameworkElement;
            }

            if (element != null)
            {
                _page = element as PhoneApplicationPage;

                if (_page != null)
                {
                    UpdateOrientation(_page.Orientation);

                    _page.OrientationChanged += new EventHandler<OrientationChangedEventArgs>(Page_OrientationChanged);
                }
            }
        }

        private void Page_OrientationChanged(object sender, OrientationChangedEventArgs e)
        {
            UpdateOrientation(e.Orientation);
        }

        private void UpdateOrientation(PageOrientation orientation)
        {
            if (orientation == PageOrientation.Landscape ||
                orientation == PageOrientation.LandscapeLeft ||
                orientation == PageOrientation.LandscapeRight)
            {
                VisualStateManager.GoToState(_page, LandscapeState, true);
            }
            else
            {
                VisualStateManager.GoToState(_page, PortraitState, true);
            }
        }
    }


}
